package edu.byu.intex2.data.dao;

import edu.byu.intex2.data.Cache;
import edu.byu.intex2.data.ConnectionPool;
import edu.byu.intex2.data.DataException;
import edu.byu.intex2.data.bo.Order;
import edu.byu.intex2.data.bo.OrderLine;
import edu.byu.intex2.data.bo.TradeInLine;
import java.sql.*;
import java.util.List;

/**
 * Order Data Access Object
 * @author Brady
 */
public class OrderDAO {

    /////////////////////////////////////////////
    ///   Singleton code
    private static OrderDAO instance = null;

    /** Creates a new instance of OrderDAO */
    private OrderDAO() {
    }//constructor

    /** Retrieves the single instance of this class */
    public static synchronized OrderDAO getInstance() {
        if (instance == null) {
            instance = new OrderDAO();
        }
        return instance;
    }//getInstance

    ////////////////////////////////////////////
    ///   CREATE methods
    /**
     * Creates a new order in the database */
    public Order create(String id) throws DataException {
        Order order = new Order(id);
        order.setObjectAlreadyInDB(false);
        Cache.getInstance().put(order.getId(), order);
        return order;
    }//create


    ////////////////////////////////////////////
    ///   READ methods
    /**
     * Reads an existing order from the database     */
    public Order read(String id) throws DataException {
        // Check Cache
        if (Cache.getInstance().containsKey(id)) {
            return (Order) Cache.getInstance().get(id);
        }

        // Get Connection
        Connection conn = ConnectionPool.getInstance().get();

        // Try Reading with connection
        try {
            return read(id, conn);
        } catch (Exception e) {
            throw new DataException("An error occurred while reading the order business object information.", e);
        } finally {
            ConnectionPool.getInstance().release(conn);
        }
    }

    /**
     * Internal method to read an existing order from the database
     * @return order
     */
    synchronized Order read(String id, Connection conn) throws Exception {
        // Check Cache
        if (Cache.getInstance().containsKey(id)) {
            return (Order) Cache.getInstance().get(id);
        }

        // Prepare a SQL Statement
        PreparedStatement stmt = conn.prepareStatement("SELECT * FROM part_order where id=?");

        try {
            stmt.setString(1, id);
            ResultSet rs = stmt.executeQuery(); // execute query
            if (rs.next()) {
                // Read the record with the result set
                return readRecord(rs, conn);
            }//if
            throw new DataException("Order with id '" + id + "' not found.");
        } finally {
            stmt.close();
        }
    }//read

    /** Internal method to create a order object from a record  */
    synchronized Order readRecord(ResultSet rs, Connection conn) throws Exception {
        if (Cache.getInstance().containsKey(rs.getString("id"))) {
            return (Order) Cache.getInstance().get(rs.getString("id"));
        }
        // Create new order object
        Order order = new Order(rs.getString("id"));

        // Order is already in DB
        order.setObjectAlreadyInDB(true);

        // Put order in cache
        Cache.getInstance().put(order.getId(), order);

        // Set Order Attributes
        order.setTotalPrice(rs.getDouble("total_price"));
        order.setTax(rs.getDouble("tax"));
        order.setDate(rs.getDate("order_date"));
        order.setTechnicianId(rs.getString("technician_id"));
        order.setServiceFacilityId(rs.getString("service_facility_id"));
        order.setServiceFacilityId(rs.getString("service_facility_id"));

        // Order is dirty and needs to be saved to DB
        order.setDirty(false);

        return order;
    }//readRecord


    /////////////////////////////////////////////
    ///   UPDATE methods
    /** Saves an existing order in the database */
    public void save(Order order) throws DataException {
        // get a connection from the pool, save all of the orders first using the other order method and then commit them in the database
        Connection conn = ConnectionPool.getInstance().get();

        try {
            save(order, conn); // save with connection
            conn.commit();  // commit the db transaction
        } catch (Exception e) {
            try {
                //rollback if there were any errors saving, catch any other errors you might have
                conn.rollback();
            } catch (SQLException e2) {
                throw new DataException("Could not roll back the order database transaction!", e2);
            }
            throw new DataException("An error occurred while saving the order object information.", e);
        } finally {
            // release the connection
            ConnectionPool.getInstance().release(conn);
        }
    }

    /** Internal method to update a order in the database */
    void save(Order order, Connection conn) throws Exception {
        // put the order object to cache
        Cache.getInstance().put(order.getId(), order);

        // decide whether to update or insert into the database
        if (order.isObjectAlreadyInDB() && order.isDirty()) {
            update(order, conn);
        } else if (order.isDirty()) {
            insert(order, conn);
        }//if

        // Save order lines
        List<OrderLine> orderLines = order.getOrdersLines();
        for (OrderLine sl : orderLines){
            OrderLineDAO.getInstance().saveNoCommit(sl, conn);
        }
    }

    /** External method to update or create a order in the database without committing connection */
    public void saveNoCommit(Order order, Connection conn, Boolean alreadyInDB) throws Exception {
        // decide whether to update or insert into the database
        if (alreadyInDB) {
            update(order, conn);
        } else {
            insert(order, conn);
        }
    }

    /** Saves an existing order to the database */
    private void update(Order order, Connection conn) throws Exception {
        // use a prepared statement to prevent sql injection
        // TODO: correct SQL Update Statement
        //      Date: 2/4/2009 - Brady White
        PreparedStatement stmt = conn.prepareStatement("UPDATE part_order SET total_price=?, tax=?, " +
                                                         "order_date=?, technician_id=?  WHERE id=?");
        try {
            // TODO: correct set statements
            //      Date: 2/4/2009 - Brady White
            // Get Order Attributes and add them to the statement
            stmt.setDouble(1, order.getTotalPrice());
            stmt.setDouble(2, order.getTax());
            stmt.setDate(7, new java.sql.Date(order.getDate().getTime()));
            stmt.setString(9, order.getTechnicianId());
            stmt.setString(10, order.getId());
            stmt.execute();

            // Order is clean!
            order.setDirty(false);
        } finally {
            stmt.close();  // make sure to close the prepared statement
        }
    }

    /** Inserts a new order into the database */
    private void insert(Order order, Connection conn) throws Exception {
        // TODO: correct SQL Insert Statement
        //      Date: 2/4/2009 - Brady White
        PreparedStatement stmt = conn.prepareStatement("INSERT INTO part_order (id, total_price, tax, financed, down_payment, payment_plan, discount, order_date, ordersperson_bonus, ordersperson_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        try {
            // TODO: correct set Statements
            //      Date: 2/4/2009 - Brady White
            // Set Order Attributes
            stmt.setString(1, order.getId());
            stmt.setDouble(2, order.getTotalPrice());
            stmt.setDouble(3, order.getTax());
            stmt.setDate(8, new java.sql.Date(order.getDate().getTime()));
            stmt.setString(10, order.getTechnicianId());
            stmt.execute();

            order.setObjectAlreadyInDB(true); // now in DB
            order.setDirty(false); // object is clean
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            stmt.close(); // close the prepared statement
        }
    }

    /////////////////////////////////////////////////
    ///   DELETE methods
    /** We do not support deleting of business objects in this application */
    public void delete(Order order) throws DataException {
        throw new RuntimeException("Nice try. The delete function is not supported in this application.");
    }

    ////////////////////////////////////////////////
    ///   SEARCH methods

}
